package com.ideal.wxlogin.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 写入一个字符串键值对
     */
    public void setString(String key, String value) {
        stringRedisTemplate.opsForValue().set(key, value);
        System.out.println("成功向Redis写入: {" + key + ": " + value + "}");
    }

    /**
     * 写入一个带过期时间的字符串键值对
     */
    public void setString(String key, String value, long timeout, TimeUnit unit) {
        stringRedisTemplate.opsForValue().set(key, value, timeout, unit);
        System.out.println("成功向Redis写入带过期时间的数据: {" + key + ": " + value + "}, 过期时间: " + timeout + " " + unit.toString());
    }


    /**
     * 根据键获取字符串值
     */
    public String getString(String key) {
        String value = stringRedisTemplate.opsForValue().get(key);
        System.out.println("从Redis读取到数据: {" + key + ": " + value + "}");
        return value;
    }

    /**
     * 删除一个键
     */
    public void deleteKey(String key) {
        stringRedisTemplate.delete(key);
        System.out.println("成功从Redis删除键: " + key);
    }

}
